/**
 * Copyright (c) 2015 Baidu. All Rights Reserved.
 *
 * @file 用于Model创建
 * @author yuanguozheng
 */
var config = require('./utils/config');
var requester = require('./utils/requester');
var dataParser = require('./utils/dataParser');
var packager = require('./utils/packager');

var fileutil = require('./utils/fileutil');
var baseOutput = fileutil.createBase();

/**
 * 发送HTTP请求获取JSON，并解析
 *
 * @param {Object} reqModel HTTP请求Model
 * @param {string} rootCls 根类名
 * @param {Function} callback 回调函数
 */
function requestJson(reqModel, rootCls, lang, prj, pkg, mapping, callback) {
    if (reqModel == null || reqModel === undefined) {
        return;
    }
    if (rootCls == null || rootCls === undefined || rootCls === '') {
        return;
    }
    requester.doReq(reqModel, function (resModel) {
        if (resModel != null && resModel.code === 200) {
            var content = resModel.body;
            var data = JSON.parse(content);
            parseJson(data, rootCls, lang, prj, pkg, mapping, function () {
                callback();
            });
        }
    });
}

/**
 * 直接处理JSON对象
 *
 * @param {Object} data JSON对象
 * @param {string} rootCls 根类名
 * @param lang
 * @param prj
 * @param pkg
 * @param mapping
 * @param callback
 */
function parseJson(data, rootCls, lang, prj, pkg, mapping, callback) {
    if (data == null || data === undefined) {
        return;
    }
    var pData;
    try {
        pData = dataParser(data, lang, rootCls);
    } catch (e) {
        console.error('解析错误');
        console.error(e);
        return;
    }
    var gener = require('./generator/' + lang);
    gener(pData, baseOutput[lang], prj, pkg, mapping, function () {
        callback();
    });
}

module.exports = {
    withRequestModel: requestJson,
    withJsonObject: parseJson
};

